<template>
  <div>
    <el-table
      @row-contextmenu="rightClick"
      border
      id="iTable"
      v-loading.iTable="options.loading"
      stripe
      :data="visibleLists"
      :stripe="false"
      ref="mutipleTable"
      empty-text=" "
      :header-cell-style="{ background: '#f6f8f8' }"
      :row-class-name="TableRowClassName"
      v-scrollbar="'.el-table__body-wrapper'"
      :max-height="maxHeight"
      :show-summary="options.showDummary"
      :summary-method="getSummaries"
    >
      <!--数据列-->
      <template v-for="(column, index) in columns">
        <template v-if="column.prop.indexOf('{') > -1">
          <template v-for="n in 10">
            <el-table-column
              :show-overflow-tooltip="column.showOverflow"
              :prop="column.prop.replace(/{id}/g, n)"
              :key="column.prop.replace(/{id}/g, n)"
              :label="column.name + n"
              :align="column.align"
              :width="hasResize ? column.showWidth : column.width"
              :sortable="column.sortable"
              v-if="
                list[0] &&
                  list[0][column.prop.replace(/{id}/g, n)] &&
                  column.show
              "
            >
            </el-table-column>
          </template>
        </template>
        <template v-else>
          <el-table-column
            :show-overflow-tooltip="column.showOverflow"
            :prop="column.prop"
            :key="column.name"
            :label="column.name"
            :align="column.align"
            :width="hasResize ? column.showWidth : column.width"
            :sortable="column.sortable"
            v-if="column.show"
          >
            <template slot="header" slot-scope="scope">
              <template
                v-if="
                  column.prop == options.expandColumn ||
                    column.prop == 'folderName'
                "
              >
                <el-checkbox
                  :indeterminate="rootList.isIndeterminate"
                  v-model="rootList.checked"
                  @change="HandleRootCheckedChange(rootList)"
                >
                </el-checkbox>
                <span
                  class="expand-icon"
                  v-if="rootList.collapsed"
                  style="background-color: #fff; border-radius: 50%"
                  @click="HandleExpandAll()"
                >
                </span>
                <span
                  class="expand-icon expanded"
                  v-else
                  style="background-color: #fff; border-radius: 50%"
                  @click="HandleExpandAll()"
                >
                </span>
              </template>
              {{ column.name }}
            </template>

            <template slot-scope="scope">
              <template
                v-if="
                  column.fullEdit != null &&
                    column.fullEdit != undefined &&
                    dynamicEval(scope.row, String(column.fullEdit)) &&
                    editall
                "
              >
                <template v-if="addFormData[column.prop] != undefined">
                  <dynamic-form-item
                    :addform="[addFormData[column.prop]]"
                    :form="scope.row"
                  >
                  </dynamic-form-item>
                </template>
                <template v-else>
                  <el-input v-model="scope.row[column.prop]"></el-input>
                </template>
              </template>
              <template v-else>
                <template v-if="!column.render">
                  <template
                    v-if="
                      column.prop == options.expandColumn ||
                        column.prop == 'folderName'
                    "
                  >
                    <el-checkbox
                      :indeterminate="scope.row.isIndeterminate"
                      v-model="scope.row.checked"
                      @change="HandleCheckedChange(scope.row)"
                      :style="{
                        marginLeft: scope.row.parents.length * 16 + 'px'
                      }"
                      :disabled="uncheck.includes(scope.row.id)"
                    >
                    </el-checkbox>
                    <span
                      class="expand-icon"
                      v-if="
                        scope.row.children.length > 0 && scope.row.collapsed
                      "
                      @click="HandleExpand(scope.row.id)"
                    >
                    </span>
                    <span
                      class="expand-icon expand"
                      v-else
                      @click="HandleExpand(scope.row.id)"
                    ></span>
                    <i
                      class="remarkpaste el-icon-s-flag"
                      v-if="scope.row.paste"
                    ></i>
                  </template>
                  <template v-if="column.propType === 'list'">
                    <template
                      v-if="
                        scope.row[column.prop] &&
                          scope.row[column.prop].length >= 1
                      "
                    >
                      <el-dropdown placement="bottom">
                        <span class="el-dropdown-link">
                          {{ scope.row[column.prop].length }}
                          <i class="el-icon-arrow-down el-icon--right"></i>
                        </span>
                        <el-dropdown-menu
                          slot="dropdown"
                          v-scrollbar
                          style="max-height: 300px; overflow: hidden; z-index: 1000"
                        >
                          <template v-for="file in scope.row[column.prop]">
                            <el-dropdown-item
                              class="item"
                              :key="file.id"
                              :command="file"
                            >
                              <a
                                style="text-decoration: underline; color: #409eff"
                                @click="
                                  preview(
                                    file.path,
                                    scope.row['stateid'],
                                    scope.row['id'],
                                    file.id
                                  )
                                "
                              >
                                {{ file.fileName }}
                              </a>
                            </el-dropdown-item>
                          </template>
                        </el-dropdown-menu>
                      </el-dropdown>
                    </template>
                    <template v-else>
                      0
                    </template>
                    <!-- <div
                          v-for="(item, index) in scope.row[column.prop]"
                          :key="index"
                        >
                          <a
                            style="text-decoration: underline; color: #409eff"
                            @click="
                              preview(
                                item.path,
                                scope.row['stateid'],
                                scope.row['docId']
                              )
                            "
                          >
                            {{ item.fileName }}
                          </a>
                        </div> -->
                  </template>
                  <template v-else-if="column.propType === 'date'">
                    <span>{{ scope.row[column.prop].split(' ')[0] }}</span>
                  </template>
                  <template v-else-if="column.propType === 'link'">
                    <span
                      class="link-type"
                      @click="jumpTo(scope.row, column)"
                      >{{ scope.row[column.prop] }}</span
                    >
                  </template>
                  <template v-else-if="column.propType === 'button'">
                    <span
                      @click="
                        clickEvent(
                          {
                            url: column.url,
                            pageParams: column.pageParams,
                            type: 1,
                            name: column.name
                          },
                          scope.row
                        )
                      "
                    >
                      {{ scope.row[column.prop] }}
                      <i class="el-icon-plus"></i>
                    </span>
                  </template>
                  <template v-else-if="column.propType === 'progress'">
                    <el-progress
                      :text-inside="true"
                      :stroke-width="26"
                      :percentage="scope.row[column.prop]"
                    >
                    </el-progress>
                  </template>
                  <template v-else-if="column.propType === 'rate'">
                    <el-rate
                      disabled
                      text-color="#ff9900"
                      v-model="scope.row[column.prop]"
                      show-score
                    >
                    </el-rate>
                  </template>
                  <template v-else-if="column.propType === 'image'">
                    <img
                      :src="scope.row[column.prop]"
                      alt="问题图片"
                      style="width: 20px; height: 20px"
                      @click="imgPreview(scope.row[column.prop])"
                    />
                  </template>
                  <template v-else-if="column.propType === 'icon'">
                    <img
                      v-if="dynamicEval(scope.row, column.pageParams)"
                      :src="dynamicEval(scope.row, column.pageParams)"
                      alt="图标"
                    />
                  </template>
                  <template v-else>
                    <template v-if="Array.isArray(scope.row[column.prop])">
                      <span
                        v-for="(item, index) in scope.row[column.prop]"
                        :key="index"
                        >{{ item }}</span
                      >
                    </template>
                    <template v-if="!Array.isArray(scope.row[column.prop])">
                      {{ dataFormat(column.prop, scope.row[column.prop]) }}
                    </template>
                  </template>
                </template>
                <template v-else>
                  <expand-dom
                    :column="column"
                    :row="scope.row"
                    :render="column.render"
                    :index="index"
                  >
                  </expand-dom>
                </template>
              </template>
            </template>
          </el-table-column>
        </template>
      </template>
      <!--end-->
      <!--按钮操作组-->
      <el-table-column
        ref="fixedColumn"
        fixed="right"
        label="操作"
        align="center"
        :width="
          operates.list.filter(_x => _x.status === '1' && _x.location === '1')
            .length <= 3
            ? operates.list.filter(
                _x => _x.status === '1' && _x.location === '1'
              ).length *
                40 +
              60
            : 100
        "
        v-if="
          operates.list.filter(_x => _x.status === '1' && _x.location === '1')
            .length > 0
        "
      >
        <template slot-scope="scope" v-if="!editall">
          <el-dropdown
            v-if="
              operates.list.filter(
                _x => _x.status === '1' && _x.location === '1'
              ).length > 3
            "
            @command="handleCommand"
          >
            <span class="el-dropdown-link">
              操作选择<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <div v-for="(btn, index) in operates.list" :key="index">
                <el-dropdown-item
                  class="item"
                  v-if="btn.status === '1' && btn.location === '1'"
                  v-show="
                    btn.show != null && btn.show != undefined && btn.show != ''
                      ? dynamicEval(scope.row, btn.show)
                      : true
                  "
                  :key="btn.id"
                  :command="{ btn, row: scope.row }"
                >
                  <el-upload
                    class="upload-demo"
                    :action="upload.url"
                    :file-list="[]"
                    :on-success="
                      (response, file, fileList) => {
                        return handleFileSuccess(
                          response,
                          file,
                          fileList,
                          scope.row,
                          btn
                        )
                      }
                    "
                    :on-error="handleFileError"
                    :headers="upload.headers"
                    :show-file-list="false"
                    :multiple="btn.operateType.indexOf('multi') > -1"
                    v-if="btn.type == '4'"
                  >
                    <el-button
                      size="mini"
                      type="text"
                      :icon="btn.icon"
                      :plain="false"
                      v-if="
                        !(
                          $route.path.indexOf('/outer') > -1 &&
                          btn.name == '删除'
                        )
                      "
                      >{{ btn.name }}
                    </el-button>
                  </el-upload>
                  <template v-else>
                    <el-button
                      size="mini"
                      type="text"
                      :icon="btn.icon"
                      :plain="false"
                      v-hasPermi="['pms:type:edit']"
                      v-if="
                        !(
                          $route.path.indexOf('/outer') > -1 &&
                          btn.name == '删除'
                        )
                      "
                      >{{ btn.name }}
                    </el-button>
                  </template>
                </el-dropdown-item>
              </div>
            </el-dropdown-menu>
          </el-dropdown>
          <div class="operate-group" v-else>
            <div v-for="(btn, index) in operates.list" :key="index">
              <div
                class="item"
                v-if="btn.status === '1' && btn.location === '1'"
                v-show="
                  btn.show != null && btn.show != undefined && btn.show != ''
                    ? dynamicEval(scope.row, btn.show)
                    : true
                "
              >
                <el-upload
                  class="upload-demo"
                  :action="upload.url"
                  :file-list="[]"
                  :on-success="
                    (response, file, fileList) => {
                      return handleFileSuccess(
                        response,
                        file,
                        fileList,
                        scope.row,
                        btn
                      )
                    }
                  "
                  :on-error="handleFileError"
                  :headers="upload.headers"
                  :show-file-list="false"
                  :multiple="btn.operateType.indexOf('multi') > -1"
                  v-if="btn.type == '4'"
                >
                  <span
                    style="cursor: pointer; color: #409eff"
                    size="mini"
                    :class="btn.icon"
                    :plain="false"
                    v-if="
                      !(
                        $route.path.indexOf('/outer') > -1 && btn.name == '删除'
                      )
                    "
                    >{{ btn.name }}
                  </span>
                </el-upload>
                <template v-else>
                  <span
                    style="cursor: pointer; color: #409eff"
                    size="mini"
                    :class="btn.icon"
                    :plain="false"
                    @click="clickEvent(btn, scope.row)"
                    v-if="
                      !(
                        $route.path.indexOf('/outer') > -1 && btn.name == '删除'
                      )
                    "
                    >{{ btn.name }}
                  </span>
                </template>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <!--end-->
    </el-table>
    <div style="padding-top:20px;float:right;font-szie:14px;color:#ccc">
      共<span style="color:#409eff">{{ list.length }}</span
      >条数据，当前展示<span style="color:#409eff">{{
        visibleLists ? visibleLists.length : 0
      }}</span
      >条
    </div>
  </div>
</template>
<!--end-->
<script>
import {
  getAddForm,
  delData,
  permissions,
  updateData,
  permissionsNoState,
  previewRecord
} from '@/api/dynamic/dynamic'
import dynamicFormItem from '@/views/components/dynamicFormItem'
import resize from '@/views/dashboard/mixins/resize'
import Base64 from '@/api/base64'
import { createUniqueString } from '@/utils'
import { getToken } from '@/utils/auth'
import { uploadObj } from '@/settings.js'
export default {
  inject: ['app'],
  name: 'dynamicTreeTable',
  mixins: [resize],
  props: {
    // 数据列表
    list: {
      type: Array,
      default: () => []
    },
    /* 需要展示的列 ===
        prop：列数据对应的属性，
        label：列名，
        align：对齐方式，
        width：列宽
      */
    columns: {
      type: Array,
      default: []
    },
    /* 操作按钮组 ===
        label: 文本，
        type :类型（primary / success / warning / danger / info / text），
        show：是否显示，
        icon：按钮图标，
        plain：是否朴素按钮，
        disabled：是否禁用，
        method：回调方法
      */
    operates: {},
    // table 表格的控制参数
    options: {
      type: Object,
      default: {
        stripe: false, // 是否为斑马纹 table
        highlightCurrentRow: false, // 是否要高亮当前行
        expandColumn: 'name'
      }
    },
    //数据更新判断
    flag: true,
    diff: 0,
    scroll: {
      type: String,
      default: 'true'
    },
    uncheck: {
      type: Array,
      default: () => {
        return []
      }
    },
    defaultSelect: Object
  },
  //组件
  components: {
    expandDom: {
      functional: true,
      props: {
        row: Object,
        render: Function,
        index: Number,
        column: {
          type: Object,
          default: null
        }
      },
      render: (h, ctx) => {
        const params = {
          row: ctx.props.row,
          index: ctx.props.index
        }
        if (ctx.props.column) params.column = ctx.props.column
        return ctx.props.render(h, params)
      }
    },
    dynamicFormItem
  },
  // 数据
  data() {
    return {
      //创建根节点
      rootList: {
        id: 0,
        label: 'root',
        children: [],
        allChildren: [],
        parents: [],
        isroot: true,
        collapsed: false,
        isIndeterminate: false,
        checked: false
      },
      //id对应列表 便于查询
      listsById: [],
      listTree: null,
      //辅助显示数据实时更新
      toggle: false,
      //已选列表
      multipleSelection: [],
      addFormData: {},
      defaultExpand: [],
      maxHeight: 200,
      newList: [],
      hasResize: false,
      // 全编辑控制
      editall: false,
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        // url: process.env.VUE_APP_BASE_API + '/common/upload',
        url: uploadObj.upload,
        // url: process.env.VUE_APP_BASE_API + "/common/S3upload",
        // 上传的文件列表
        showFileList: [],
        // 大小限制(MB)
        fileSize: 500
      }
    }
  },
  created() {
    let defaultExpand = sessionStorage.getItem(
      'expand' + this.$route.query.type + this.$route.params.Id
    )
    if (defaultExpand) this.defaultExpand = eval(defaultExpand)

    if (this.$parent.$el) {
      // this.rend = true
      setTimeout(this.tableresize(), 1000)
    }
  },
  mounted() {
    setTimeout(() => {
      if (this.defaultSelect && this.listsById) {
        for (let item in this.defaultSelect) {
          for (let row of this.defaultSelect[item]) {
            if (row) {
              if (typeof row == 'string') {
                row = row.trim()
              }
              this.listsById[row].checked = true
            }
            this.toggle = !this.toggle
          }
        }
      }
    }, 1000)
  },
  watch: {
    list(val) {
      // console.log(val,this.flag)
      if (val && this.flag) {
        this.UpdateList(val)
        this.toggle = !this.toggle
      }
    }
  },
  computed: {
    //可视数据
    visibleLists() {
      if (!this.flag) {
        this.toggle = !this.toggle
        if (this.newList.length == 0) return []
        const visibleLists = this.newList.filter(item =>
          this.IsListVisible(item)
        )
        return visibleLists
      }
      return []
    }
  },
  methods: {
    UpdateList(val) {
      console.log(val, 'val')
      // if (val[1] && val[1].rank) this.SortList(val);
      this.newList = []
      this.rootList = {
        id: 0,
        label: 'root',
        children: [],
        allChildren: [],
        parents: [],
        isroot: true,
        collapsed: false,
        isIndeterminate: false,
        checked: false
      }
      this.listsById = this.ResetListTree(val)
      // if(val[1].rank)
      this.SortList(val)
      console.log(this.rootList, 'vallll')
      this.listTree = this.MakeListTree(this.rootList, val)
      this.newList = this.SortList2(this.rootList)
      for (let item of this.rootList.children) {
        this.GetList(item).collapsed = false
      }
      this.SetFlag()
    },
    // 排序方法1
    SortList(val) {
      if (val[0] && val[0].rank) {
        let tempIndex = 0
        let firstList = val.filter((item, index) => {
          // console.log(item,index)
          if (item.rank == '1') {
            tempIndex = index
            return item
          }
        })[0]
        if (tempIndex != 0) {
          let tempList = val[0]
          firstList.rowIndex = '0'
          tempList.rowIndex = tempIndex.toString()
          val[0] = firstList
          val[tempIndex] = tempList
        }
      }
    },
    // 排序方法2
    SortList2(parentList) {
      var newList = []
      if (parentList.children && parentList.children.length > 0) {
        for (let li of parentList.children) {
          let item = this.GetList(li)
          newList.push(item)
          let appendList = this.SortList2(item)
          if (appendList.length > 0) {
            newList = newList.concat(appendList)
          }
        }
      }
      return newList
    },

    ResetListTree(lists) {
      const listById = {}
      var startLevel
      for (let i in lists) {
        let current = lists[i]
        current.rowIndex = i
        current.parentid =
          current.parentid == -1
            ? 0
            : current.parentid == 0 && current.rank
            ? current.projectid
            : current.parentid
        console.log(i, 'iiii')
        // if (i == 0) {
        //   this.rootList.id = current.rank && this.$route.params.Id == current.projectid
        //       ? current.projectid
        //       : current.parentid
        //   startLevel = current.level || 0
        // }
        current.checked = false
        current.isIndeterminate = false
        current.children = []
        current.allChildren = []
        current.parents = []
        if (this.defaultExpand.indexOf(current.id) > -1)
          current.collapsed = false
        else current.collapsed = true
        listById[current.id] = current
      }
      return listById
    },
    // 树级结构数据生成
    MakeListTree(list, lists) {
      console.log(list, 'list')
      console.log(lists, 'lists')
      for (let current of lists) {
        if (current.parentid == list.id) {
          if (list.parents.length) {
            list.parents.forEach(parent => current.parents.push(parent))
          }
          if (list.isroot !== true) {
            current.parents.push(list.id)
            current.parentid = list.id
          }
          current = this.MakeListTree(current, lists)
          list.allChildren.push(current.id)
          list.children.push(current.id)
          current.allChildren.forEach(childId => list.allChildren.push(childId))
        }
      }
      return list
    },
    // 行是否显示判断
    IsListVisible(list) {
      if (typeof list === 'number' || typeof list === 'string') {
        list = this.GetList(list)
      }
      if (list.parents.length > 0) {
        for (let i = 0, len = list.parents.length; i < len; i++) {
          let item = this.GetList(list.parents[i])
          if (item.collapsed) {
            return false
          }
        }
      }
      return true
    },
    // 获取行
    GetList(listId) {
      if (typeof this.listsById[listId] !== 'undefined') {
        return this.listsById[listId]
      }
      return null
    },
    // 根折叠框回调
    HandleExpandAll() {
      this.rootList.collapsed = !this.rootList.collapsed
      for (let item of this.rootList.allChildren) {
        let list = this.GetList(item)
        list.collapsed = this.rootList.collapsed
      }
      if (this.rootList.collapsed) this.defaultExpand = []
      else
        this.defaultExpand = [this.rootList].concat(
          this.list.map(item => {
            return item.id
          })
        )
      sessionStorage.setItem(
        'expand' + this.$route.query.type + this.$route.params.Id,
        JSON.stringify(this.defaultExpand)
      )
      this.toggle = !this.toggle
    },
    // 折叠框回调
    HandleExpand(id) {
      let list = this.GetList(id)
      list.collapsed = !list.collapsed
      if (list.collapsed) {
        let index = this.defaultExpand.indexOf(id)
        this.defaultExpand.splice(index, 1)
      } else {
        this.defaultExpand.push(id)
      }
      sessionStorage.setItem(
        'expand' + this.$route.query.type + this.$route.params.Id,
        JSON.stringify(this.defaultExpand)
      )
      this.rootList.collapsed = this.HandleRootCollapsed()
      this.toggle = !this.toggle
    },
    //行点击事件
    jumpTo(row, column) {
      let params = {}
      let pageParams = JSON.parse(column.pageParams.replace(/'/g, '"'))
      pageParams.url = column.url
      params.pageParams = pageParams
      params.rowParams =
        pageParams.route.indexOf('projectid') > -1
          ? { name: row.projectName }
          : row
      params.type = column.url.replace(/\/{id}|\/{projectid}/g, '')
      if (
        this.$route.query.type &&
        this.$route.query.type.indexOf('template') > -1 &&
        params.type == '/pmswbs'
      ) {
        params.edit = 'pmswbs/editTemplateWbs'
      }
      if (pageParams.route.indexOf('{') > -1) {
        pageParams.route = this.getUrl(pageParams.route, row)
        // console.log(pageParams.route)
      } else {
        pageParams.route = pageParams.route + '/' + row.id
      }
      if (this.$route.path.indexOf('/outer') > -1) {
        let routeData = this.$router.resolve({
          path: '/outer/dynamic/' + pageParams.route,
          query: params
        })
        const newwin = window.open(
          routeData.href,
          createUniqueString(),
          `height=${
            0.5 * this.app.screenHeight > 600
              ? 0.5 * this.app.screenHeight
              : 600
          },
                                    width=${
                                      0.5 * this.app.screenWidth > 960
                                        ? 0.5 * this.app.screenWidth
                                        : 960
                                    },
                                    top=${0.2 * this.app.screenHeight},
                                    left=${0.2 * this.app.screenWidth}`
        )
        newwin.route = routeData.route
      } else {
        this.$router.push({
          path: '/dynamic/' + pageParams.route,
          query: params
        })
      }
    },
    // 按钮点击事件
    clickEvent(obj, row) {
      let pageParams = JSON.parse(obj.pageParams.replace(/'/g, '"'))
      if (obj.type === '2') {
        if (obj.url) {
          let params = {}
          pageParams.url = obj.url
          params.rowParams = row
          params.pageParams = pageParams
          params.pageParams.title = obj.description
          this.$router.push({
            path: '/dynamic/' + pageParams.route + '/' + row.id,
            query: params
          })
        }
      } else {
        if (pageParams.handle == 'handleUpdate') {
          this.handleUpdate(obj.url, pageParams.addForm, row)
        } else if (pageParams.handle == 'handleTable') {
          this.handleTable(obj.url, pageParams, row.id, obj.description)
        } else if (pageParams.handle == 'handleDelete') {
          this.handleDelete(obj.url, obj.description, row)
        } else if (pageParams.handle == 'handleConfirm') {
          this.handleConfirm(obj.url, pageParams.method, obj.description, row)
        }
      }
    },
    //修改
    handleUpdate(url, str, row) {
      if (
        row.parentid == 0 &&
        this.dataFormat('typeid', row.typeid).indexOf('项目') > -1
      ) {
        url = this.$route.query.type
        str = 'add_' + this.$route.query.type.trim('/')
      }
      let info = { url, str, id: row.id }
      this.$emit('editChanged', info)
    },
    /** 删除按钮操作 */
    handleDelete(url, title, row) {
      const id = row.name || row.title || row.fileName || row.folderName
      this.$confirm(`是否确认${title} "${id}"?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          return delData(url, row.id)
        })
        .then(() => {
          // var obj={pageNum: 1, pageSize: 10};
          this.refreshCurrent()
          this.msgSuccess('删除成功')
        })
        .catch(function() {})
    },
    // 确定弹框
    handleConfirm(url, method, title, row) {
      this.$confirm(
        `确定${title} "${row.name ||
          row.title ||
          row.fileName ||
          row.folderName}"?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          baseRequest('/pms' + this.getUrl(url, row), method, {}, {}).then(
            response => {
              if (response.code == 200) {
                this.msgSuccess(response.msg)
                this.refreshCurrent()
                return true
              } else {
                this.msgError(response.msg)
                return true
              }
            }
          )
        })
        .catch(() => {
          this.msgInfo('已取消')
        })
    },
    //preview预览
    preview(previewUrl, stateId, docId, fileId) {
      if (stateId === undefined) {
        permissionsNoState('views', docId).then(response => {
          if (response !== 1) {
            this.msgError('您没有此状态下数据的【预览】权限！')
          } else {
            this.previewActions(previewUrl)
            if (docId && fileId) {
              previewRecord(docId, fileId)
            }
          }
        })
      } else {
        permissions('views', stateId).then(response => {
          if (response !== 1) {
            this.msgError('您没有此状态下数据的【预览】权限！')
          } else {
            this.previewActions(previewUrl)
            if (docId && fileId) {
              previewRecord(docId, fileId)
            }
          }
        })
      }
    },
    // 预览操作
    previewActions(previewUrl) {
      if (previewUrl == null || previewUrl === '') {
        this.msgError('预览预览地址错误！')
      }
      var close = false
      const Loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      setTimeout(() => {
        if (!close) {
          Loading.close()
          this.msgError('预览加载超时,请稍后重试或联系管理员。')
        }
      }, 10000)
      const screenWidth = parseInt(0.5 * document.body.clientWidth) // 预览窗口宽度
      const screenHeight = parseInt(0.6 * document.documentElement.clientHeight) // 预览窗口高度
      var strLength = previewUrl.length
      var str = previewUrl.slice(previewUrl.indexOf('.') + 1, strLength)

      /** 30 预览
      let previewParam = {};
      var url = previewParameter.preview_path;
      previewParam.url = previewParameter.server_url_port;
      previewParam.accesskey = previewParameter.access_key;
      previewParam.secretkey = previewParameter.secret_key;
      previewParam.bucket = str;
      var index = previewUrl.lastIndexOf("/");
      var bucket = previewUrl.substring(0, index);
      var file = previewUrl.substring(index + 1, previewUrl.length);
      previewParam.bucket = bucket;
      previewParam.file = file;
      //水印
      var watermark = this.$store.state.user.name;

      let xhr = new XMLHttpRequest();
      xhr.open("POST", url, true); //建立间接，要求异步响应
      xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //设置为表单方式提交
      xhr.onreadystatechange =  ()=>{
        //绑定响应状态事件监听函数
        if (xhr.readyState == 4) {
          //监听readyState状态
          if (xhr.status == 200 || xhr.status == 0) {
            //监听HTTP状态码
            if(xhr.responseText==="" || xhr.responseText==null){
              Loading.close();
              close = true
              var rdata = JSON.parse(xhr.responseText);
              if (rdata.success) {
                window.open(
                  rdata.viewurl,
                  "previewwindow",
                  `height=${screenHeight},
                            width=${screenWidth},
                            top=${0.4 * screenHeight},
                            left=${0.5 * screenWidth}`
                );
              }else{
                this.msgError(rdata.msg);
              }
            }else{
              Loading.close();
              close = true
              this.msgError("预览文件错误");
            }
          }
        }
      };
      let data = Base64.encode(previewParam);
      xhr.send("file=" + encodeURIComponent(data)+"&watermark="+watermark+"&cache=false"); //发送请求
      /** 30 预览*/

      /** 120 预览*/
      let strArray = ['img', 'png', 'html']
      var url = ''
      if (previewUrl.indexOf('http://') < 0) {
        url = this.settings.fileUrl + previewUrl
        // url = "http://8.135.99.28:81" + previewUrl;
      } else {
        url = previewUrl
      }
      console.log(url)
      if (strArray.indexOf(str) > -1) {
        Loading.close()
        close = true
        if (0) url = 'http://localhost:81' + previewUrl
        window.open(
          url,
          createUniqueString(),
          `height=${screenHeight},
                    width=${screenWidth},
                    top=${0.4 * screenHeight},
                    left=${0.5 * screenWidth}`
        )
      } else {
        Loading.close()
        close = true
        window.open(
          this.settings.previewUrl +
            '/onlinePreview?url=' +
            encodeURIComponent(Base64.encode(url)),
          createUniqueString(),
          `height=${screenHeight},
                    width=${screenWidth},
                    top=${0.4 * screenHeight},
                    left=${0.5 * screenWidth}`
        )
      }
      /** 120 预览*/
    },
    handleTable(url, str, id, title) {
      let info = { url, str, id, title }
      this.$emit('openTable', info)
    },
    // 根折叠状态判断
    HandleRootCollapsed() {
      if (this.rootList.children.length === 0) {
        return false
      }
      let collapsed = 0
      for (let item of this.rootList.children) {
        if (this.GetList(item).collapsed) {
          collapsed++
        }
      }
      return collapsed === this.rootList.children.length
    },
    // 表格行类名回调
    TableRowClassName(item) {
      let className = ''
      if (
        item.row.percent < 100 &&
        new Date().valueOf() - new Date(item.row.esfinishdate).valueOf() > 0
      ) {
        className += ' expired'
      }
      if (this.options.stripe && item.rowIndex % 2 == 1) {
        className += ' striped'
      }
      if (item.row.paste != undefined) {
        className += ' paste'
      }
      if (item.row.cut != undefined) {
        className += ' cut'
      }
      return className
    },
    // 根选择框回调
    HandleRootCheckedChange(row) {
      let checked = row.checked
      if (row.allChildren.length > 0) {
        for (let item of row.allChildren) {
          let list = this.GetList(item)
          list.checked = checked
          list.isIndeterminate = false
        }
      }
      row.isIndeterminate = false
      this.toggle = !this.toggle
      this.UpdateCheckBox(row)
      this.multipleSelection = this.newList.filter(item => item.checked)
      this.$emit('handleSelectionChange', this.multipleSelection)
    },
    // 选择框回调
    HandleCheckedChange(row) {
      row.isIndeterminate = false
      this.toggle = !this.toggle
      this.UpdateCheckBox(row)
      this.multipleSelection = this.newList.filter(item => item.checked)
      this.$emit('handleSelectionChange', this.multipleSelection)
    },
    // 选择框更新
    UpdateCheckBox(row) {
      if (this.multipleSelection.length == 0) {
        //根选择框
        this.rootList.checked = false
        this.rootList.isIndeterminate = false
        //父选择框
        if (row.parents.length > 0) {
          for (let item of row.parents) {
            let list = this.GetList(item)
            list.checked = false
            list.isIndeterminate = false
          }
        }
      }
      if (
        this.multipleSelection.length > 0 &&
        this.multipleSelection.length < this.list.length
      ) {
        this.rootList.checked = false
        this.rootList.isIndeterminate = true
        if (row.parents.length > 0) {
          for (let item of row.parents) {
            let parentList = this.GetList(item)
            if (row.checked) {
              parentList.isIndeterminate = parentList.checked ? false : true
            }
          }
        }
        if (!row.checked && row.allChildren.length > 0) {
          row.isIndeterminate = false
          for (let item of row.allChildren) {
            let childItem = this.GetList(item)
            if (childItem.checked) {
              row.isIndeterminate = true
              break
            }
          }
        }
      }
      if (this.multipleSelection.length == this.list.length) {
        //根选择框
        this.rootList.checked = true
        this.rootList.isIndeterminate = false
        //父选择框
        if (row.parents.length > 0) {
          for (let item of row.parents) {
            let list = this.GetList(item)
            list.checked = true
            list.isIndeterminate = false
          }
        }
      }
    },
    SetFlag() {
      this.$emit('SetFlag')
    },
    // 右键菜单自定义
    rightClick(row, column, event) {
      event.preventDefault()
      this.$emit('ContextMenu', event)
    },
    // 表格自适应更新方法
    tableresize() {
      if (this.$refs.mutipleTable) {
        // let el = this.$refs.mutipleTable.$el
        let newDiff =
          this.diff + (this.$route.path.indexOf('outer') > -1 ? 50 : 0)
        if (this.scroll == 'false') {
          this.maxHeight =
            this.app.screenHeight - newDiff > 200
              ? this.app.screenHeight - newDiff
              : 200
        } else if (this.scroll == 'fix') {
          this.maxHeight = 200
        } else {
          this.maxHeight =
            this.$parent.$el.offsetHeight - newDiff > 200
              ? this.$parent.$el.offsetHeight - newDiff
              : 200
        }
        // if (
        //   this.scroll ||
        //   this.$refs.mutipleTable.$refs.bodyWrapper.scrollHeight >
        //     this.maxHeight
        // ) {
        //   this.maxHeight =
        //     this.$parent.$el.offsetHeight - this.diff > 200
        //       ? this.$parent.$el.offsetHeight - this.diff
        //       : 200;
        // }
        this.$refs.mutipleTable.$refs.bodyWrapper.scrollTo(0, 0)
      }
      this.widthUpdate(this.columns)
    },
    // 表格自适应更新方法
    widthUpdate(val) {
      if (val && this.$parent.$el) {
        var parentWidth = this.$parent.$el.offsetWidth
        var sum = 0
        for (let column of val) {
          if (column.width) {
            if (column.show) sum += Number(column.width)
          } else {
            sum = 0
            break
          }
        }
        // if (this.options.mutiSelect) parentWidth -= 48;
        if (
          this.operates.list.filter(
            _x => _x.status === '1' && _x.location === '1'
          ).length > 0
        ) {
          parentWidth -= 150
        }
        if (sum && sum < parentWidth) {
          this.hasResize = true
          for (let column of val) {
            column.showWidth = (column.width / sum) * parentWidth
          }
        } else {
          this.hasResize = false
        }
      }
    },
    // 表格底部合计方法
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const values = data.map(item =>
          item[column.property]
            ? Number(this.dataFormat(column.property, item[column.property]))
            : 0
        )
        if (values.every(value => !isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    // 文件上传成功回调
    handleFileSuccess(response, file, fileList, row, btn) {
      console.log(fileList)
      if (fileList.every(file => file.response != undefined)) {
        // 更新
        if (btn.operateType.indexOf('Update') > -1) {
          row.fileList = fileList.map(item => {
            return {
              fileName: item.name,
              path: item.response ? item.response.fileName : '',
              fileSize: item.size
            }
          })
        } else {
          // 叠加上传
          if (row.fileList == undefined) {
            row.fileList = []
          }
          row.fileList = row.fileList.concat(
            fileList.map(item => {
              return {
                fileName: item.name,
                path: item.response ? item.response.fileName : '',
                fileSize: item.size
              }
            })
          )
        }
        updateData(this.getUrl(btn.url), row)
          .then(() => {
            this.msgSuccess('更新成功')
            this.refreshCurrent()
          })
          .catch(err => {
            this.msgError('更新失败')
            console.log(err)
          })
      }
    },
    handleFileError() {
      this.msgInfo('文件上传失败')
    }
  }
}
</script>

<style lang="scss">
.expand-icon {
  width: 14px;
  height: 14px;
  display: inline-block;
  vertical-align: middle;
  background-size: contain !important;
  cursor: pointer;
  background: url('../../assets/image/add.png') no-repeat;
}
.expand {
  background: url('../../assets/image/minus.png') no-repeat;
}
.operate-group {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
}
.el-table th.is-leaf,
.el-table td {
  border-bottom: 0;
}
.link-type {
  text-decoration: underline;
  cursor: pointer;
}
.item {
  padding: 0 3px;
}
.el-table .striped {
  background: #fafafa !important;
}
.el-table .expired {
  color: #f56c6c !important;
}
.el-table .cut {
  color: #f56c6c !important;
  text-decoration: line-through !important;
}
.el-table .paste {
  color: #128303 !important;
}
.remarkpaste {
  color: #128303 !important;
}
.cell {
  width: 100% !important;
}
</style>
